package OpenFeign知识;

import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpExchange;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;

public class MockHttpServer {

    public static void main(String[] args) throws Exception {
        // 创建一个简单的 HTTP 服务器
        HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
        server.createContext("/users", new UserHandler());
        server.setExecutor(null); // 默认线程池
        server.start();

        System.out.println("Server started at http://localhost:8080/");
    }

    static class UserHandler implements HttpHandler {

        @Override
        public void handle(HttpExchange exchange) throws IOException {
            String method = exchange.getRequestMethod();

            if ("GET".equals(method)) {
                String userId = exchange.getRequestURI().getPath().split("/")[2];
                User user = new User(userId, "John Doe", 30);
                String jsonResponse = new ObjectMapper().writeValueAsString(user);

                exchange.getResponseHeaders().add("Content-Type", "application/json");
                exchange.sendResponseHeaders(200, jsonResponse.getBytes().length);
                OutputStream os = exchange.getResponseBody();
                os.write(jsonResponse.getBytes());
                os.close();
            }

            if ("POST".equals(method)) {
                // 读取请求体
                InputStream inputStream = exchange.getRequestBody();
                User newUser = new ObjectMapper().readValue(inputStream, User.class);
                String jsonResponse = new ObjectMapper().writeValueAsString(newUser);

                // 设置响应头和返回体
                exchange.getResponseHeaders().add("Content-Type", "application/json");
                exchange.sendResponseHeaders(200, jsonResponse.getBytes().length); // 返回 HTTP 200 状态码
                OutputStream os = exchange.getResponseBody();
                os.write(jsonResponse.getBytes());
                os.close();
            }
        }
    }
}
